package com.krt.common;

import com.krt.user.entity.FMenu;
import com.krt.user.entity.SMenu;
import com.krt.user.entity.User;
import com.krt.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by 陈汉帅 on 2017-12-24.
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
    *@Description:登录验证
    *@Data:10:31 2017-12-24
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //usernamePasswordToken用于获取前台传来的用户名和密码
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        //得到用户名
        String username=usernamePasswordToken.getUsername();
        //得到密码
        String password= String.valueOf(usernamePasswordToken.getPassword());
        //先比对用户名，密码有密码比对器
        User user=userService.checkLogin(username);
        if (user == null) {
            return null;
        } else {
            //将信息保留在shiro中
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), this.getName());
            //将user保存在session中
            SecurityUtils.getSubject().getSession().setAttribute("userInfo",user);
            //return到密码比对器CustomCredentialsMatcher
            return info;
        }
    }

    /**
    *@Description:登录成功后授权
    *@Data:10:31 2017-12-24
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();
        //多表连接，查询出二菜单和一菜单
        User user = userService.findByUser(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole(String.valueOf(user.getRoleId()));
        for (SMenu sMenu:user.getsMenuList()) {
            //赋予菜单action的权限
            authorizationInfo.addStringPermission(sMenu.getAdress());
            authorizationInfo.addStringPermission(sMenu.getFmenu().getfName());
        }
        return authorizationInfo;
    }
}
